﻿using System.Text;
using System.Web;

namespace Single.WebApp.Components
{
    public static class RequestUtility
    {
        public static bool QueryValue<T>(HttpContext context, string key, out T value)
        {
            value = default;

            Microsoft.Extensions.Primitives.StringValues queryValues;

            if (context.Request.Query.TryGetValue(key, out queryValues))
            {
                try
                {
                    string str = queryValues.FirstOrDefault();

                    str = HttpUtility.UrlDecode(str);

                    value = (T)Convert.ChangeType(str, typeof(T)); return true;
                }
                catch { return false; }
            }

            return false;
        }

        public static string QueryValue(HttpContext context, string key)
        {
            if (QueryValue(context, key, out string value))
            {
                return value;
            }

            return string.Empty;
        }

        public static string GetDomain(HttpRequest request)
        {
            return $"{request.Scheme}://{request.Host}";
        }

        public static string GetAbsoluteUri(HttpRequest request)
        {
            return $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{request.QueryString}";
        }

        public static string RemoveUrlParam(string url, string param)
        {
            var lowerUrl = url.ToLower();
            var lowerParam = param.ToLower();
            if (lowerUrl.IndexOf("&" + lowerParam) > 0)
            {
                var beginUrl = url.Substring(0, lowerUrl.IndexOf("&" + lowerParam));
                var endUrl = url.Substring(lowerUrl.IndexOf("&" + lowerParam) + 1, url.Length - lowerUrl.IndexOf("&" + lowerParam) - 1);
                if (endUrl.IndexOf("&") > 0)
                    endUrl = endUrl.Substring(endUrl.IndexOf("&"), endUrl.Length - endUrl.IndexOf("&"));
                else
                    endUrl = "";
                return beginUrl + endUrl;
            }
            if (lowerUrl.IndexOf("?" + lowerParam) > 0)
            {
                var beginUrl = url.Substring(0, lowerUrl.IndexOf("?" + lowerParam));
                var endUrl = url.Substring(lowerUrl.IndexOf("?" + lowerParam) + 1, url.Length - lowerUrl.IndexOf("?" + lowerParam) - 1);
                if (endUrl.IndexOf("&") > 0)
                    endUrl = "?" + endUrl.Substring(endUrl.IndexOf("&") + 1, endUrl.Length - endUrl.IndexOf("&") - 1);
                else
                    endUrl = "";
                return beginUrl + endUrl;
            }
            return url;
        }
    }
}